package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author ZW
 * @DATE 2020/7/24 20:05
 * @Description  搜索服务
 **/
@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap, Model model){
        Map resultMap = searchService.search(searchMap);
        model.addAttribute("searchMap",searchMap);
        model.addAttribute("result",resultMap);

        //封装分页数据并返回
        /*
            第一个参数：总记录数
            第二个参数：当前页
            第三个参数：每页显示多少条
         */
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),Page.pageSize);

        model.addAttribute("page",page);

        //拼装url
        StringBuilder url = new StringBuilder("/search/list");//给定一个初始值
        if (searchMap != null && searchMap.size() > 0){
            //代表searchMap中是有查询条件的
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!paramKey.equals("sortRule") && !paramKey.equals("sortField") && !paramKey.equals("pageNum")){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }
            String urlString = url.toString();
            //去除路径上最后一个&
            urlString = urlString.substring(0,urlString.length()-1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }
        return "search";
    }

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){
        Map searchResult = searchService.search(searchMap);
        return searchResult;
    }
}
